<?php
ArrowController::importModel("resources.ArrowResource");

/**
 * Arrow resources structure
 * 
 * @version 1.0
 * @license  GNU GPL
 * @author Artur Kmera <artur.kmera@arrowplatform.org> 
 */
class ArrowResources{

	/**
	 * Resources dir
	 * 
	 * @var String
	 */
	const RESOURCES_DIR = "/resources";
	
	/**
	 * Project reference
	 *
	 * @var ArrowProject
	 */
	private $projectReference;
	
	/**
	 * Instance
	 * 
	 * @var ArrowResources
	 */
	private static  $selfInstance = null;

	/**
	 * Singleton !NO_REMOTE
	 * 
	 * @return ArrowResources
	 */
	public static function getDefault( ArrowProject $project ) {
		if (self :: $selfInstance == null ) {
			self :: $selfInstance = new ArrowResources( $project );
		}
		return self :: $selfInstance;
	}
	
	/**
	 * Sets resources project
	 */
	private function __construct( ArrowProject $project ){
		$this->projectReference = $project;
	}
	
	/**
	 * Handle for template link:template tags
	 *
	 * @param String $path String Mapping path
	 * @param boolean $strict If true method will throw exception if file doesn't exists 
	 * @return ArrowResource
	 */	
	public function getResource( $path, $strict = true, $createIfNotExists = false ){
		$resourcePath = $this->projectReference->getPath().self::RESOURCES_DIR.$path;
		//TODO wprowadzic resourceException
		if($createIfNotExists) $strict = true;
		if( $strict && !file_exists( $resourcePath ) ){
			if($createIfNotExists){
				$resource = new ArrowResource( $this, $path );
				$resource->setContents("");
				return $resource;
			}else
				throw new ArrowCoreException( array(  "src" => "ArrowResources", "msg" => "Resource dosn't exist", "path" => $resourcePath ) );
		}
		
		return new ArrowResource( $this, $path );
	}
	
	/**
	 * Returns project reference
	 *
	 * @return ArrowProject
	 */
	public function getProjectReference(){
		return $this->projectReference;
	}
	
	/**
	 * Returns project reference
	 *
	 * @return ArrowProject
	 */
	public function makeDir($path){
		$resourcePath = $this->projectReference->getPath().self::RESOURCES_DIR.$path;
		return mkdir( $resourcePath );
	}
	
}
?>
